package com.put.mybills.activities;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.put.mybills.R;
import com.put.mybills.adapter.GlobalParams;
import com.put.mybills.database.FactureDataSource;
import com.put.mybills.database.UnitDataSource;
import com.put.mybills.model.Facture;
import com.put.mybills.model.Unit;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.NumberPicker;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class AddNewFactureActivity extends Activity {
	
	final Context context = this;
	
	private EditText newFactureName;
	private EditText newFactureDescription;
	private FactureDataSource datasource;
	private UnitDataSource unitdatasource;
	private ImageButton factureIcon;
	
	private TableLayout unitResultTable;
	
	private ImageButton addUnit;
	private ImageButton delUnit;	
	
	
	private String FactureIconPath;
	private Bitmap factureImage;
	
	private EditText unitName;
	private EditText unitPrice;
	private EditText unitMetric;
	
	//private CheckBox ifEmail;
	private CheckBox ifPopup;
	
	private TextView unitResult;
	
	private LinkedList<List<String>> unitStack = new LinkedList<List<String>>();
	private Integer factureInterval = 0;
	
	static final int GALLERY_REQUEST = 99;
	static final int CAMERA_REQUEST = 100;
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main_add_facture, menu);    	
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
			
		switch (item.getItemId()) {
        case R.id.save_facture:
        	Boolean reuslt = saveFacture();        	
        	if (reuslt.equals(true))
        		super.onBackPressed();        		
            return true;	
		
		case R.id.discard_facture:			
			super.onBackPressed();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	
	public void alert(String message) {
		new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)	        
        .setMessage(message)
        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) { }

        })  
        .show();
	}
	
	
	public Boolean saveFacture() {
		
		
		if (newFactureName.getText().toString().equals("") ){
			alert(getResources().getString(R.string.new_facture_notemptyname));			
			return false;				
		}
		else if (datasource.getFacture(newFactureName.getText().toString()) != null) {
			alert(getResources().getString(R.string.new_facture_exsist));				
			return false;
		
		}
		else {
			Facture newFacture = new Facture();
			newFacture.setName(newFactureName.getText().toString());			
			newFacture.setIcon(FactureIconPath);
			newFacture.setDescripiton(newFactureDescription.getText().toString());
			Log.d("ADDFACTURE", "INTERVAL  = " + factureInterval);
			newFacture.setInterval(factureInterval);
			//newFacture.setIsEmalNotyfication(ifEmail.isChecked() ? 0 :1);
			newFacture.setIsPopUpNotyfication(ifPopup.isChecked() ? 0 :1);
	
			
			datasource.createFacture(newFacture);
			
			for (List<String> st : unitStack) {		
				Unit newUnit = new Unit();
				newUnit.setName(st.get(0));
				try {
					newUnit.setPrice(Double.parseDouble(st.get(1)));			
				}
				catch (NumberFormatException e) {
					
				}
				newUnit.setMetric(st.get(2));
				newUnit.setFactureID(datasource.getFacture(newFacture.getName()).getId());
				
				unitdatasource.createUnit(newUnit);
			}
			return true;
		}
	
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);			
		setContentView(R.layout.activity_add_new_facture); 
		
		datasource = new FactureDataSource(this);
		datasource.open();
		
		unitdatasource = new UnitDataSource(this);
		unitdatasource.open();

		newFactureName = (EditText) findViewById(R.id.new_facture_name);
		newFactureDescription = (EditText) findViewById(R.id.new_facture_description);
		
		unitResultTable = (TableLayout)  findViewById(R.id.table_units_result);	
		//ifEmail = (CheckBox) findViewById(R.id.new_facture_email_notyfication_chexbox);
		ifPopup = (CheckBox) findViewById(R.id.new_facture_pushup_notyfication_chexbox);

		
		NumberPicker numberPicker = (NumberPicker) findViewById(R.id.new_facture_interval);
	    numberPicker.setMaxValue(100);       
	    numberPicker.setMinValue(0);        
	    numberPicker.setWrapSelectorWheel(true);
	    numberPicker.setOnValueChangedListener( new NumberPicker.
	        OnValueChangeListener() {
	        @Override
	        public void onValueChange(NumberPicker picker, int
	            oldVal, int newVal) {
	        	
	        	factureInterval = newVal;
	           
	        }
	     });
		

		factureIcon = (ImageButton) findViewById(R.id.new_facture_image);		
		factureIcon.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				final Dialog dialog = new Dialog(context);
				dialog.setContentView(R.layout.dialog_image_chooser);
				dialog.setTitle(R.string.imageFromTitle);				
				
				Button galleryDialogButton = (Button) dialog.findViewById(R.id.image_from_gallery);				
				galleryDialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
						Intent intent = new Intent();
						intent.setAction(Intent.ACTION_GET_CONTENT);  
			            intent.setType("image/*");
			            startActivityForResult(intent, GALLERY_REQUEST);						
						dialog.dismiss();
					}
				});
				
				Button cameraDialogButton = (Button) dialog.findViewById(R.id.image_from_camera);				
				cameraDialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");       
					    startActivityForResult(intent, CAMERA_REQUEST);
						dialog.dismiss();
					}
				});
	 
				dialog.show();

			}
		});
		
		addUnit  = (ImageButton) findViewById(R.id.add_units);		
		delUnit  = (ImageButton) findViewById(R.id.delete_units);		
		
        unitName = (EditText) findViewById(R.id.unit_name_value);		
      	unitPrice = (EditText) findViewById(R.id.unit_price_value);		
      	unitMetric = (EditText) findViewById(R.id.unit_metric_value);	
      	
      	//unitResult = (TextView) findViewById(R.id.new_facture_units_result);
      	
      	addUnit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				  
				String un = unitName.getText().toString();
				String up = unitPrice.getText().toString();
				String um = unitMetric.getText().toString();
				
				List<String> unitList = new ArrayList<String>();
				unitList.add(un);
				unitList.add(up);
				unitList.add(um);
				
				if (un != "" && up != "")				
					unitStack.addLast(unitList);
				
				printStackToTextView();
				
			}
		});
		 
		
		 delUnit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if (unitStack.size()>0)
					unitStack.removeLast();
				
				printStackToTextView();
			}
		});
	}
	
	public void printStackToTextView() {		
		createTableUnitResult();		
	}
	
	
	  public void createTableUnitResult() {
	    	
	    	unitResultTable.removeAllViews();

		 	for (List<String> st : unitStack) {	
		 		
		 		TableRow row = new TableRow(this);

			    TextView unitName = new TextView(this);
			    TextView unitPrice = new TextView(this);
			    TextView unitMetric = new TextView(this);	
			    
			    unitName.setText(st.get(0));
			    unitName.setBackgroundResource(R.drawable.cell_shape);
			    
			    unitPrice.setText(st.get(1));
			    unitPrice.setBackgroundResource(R.drawable.cell_shape);
			    
			    unitMetric.setText(st.get(2));
			    unitMetric.setBackgroundResource(R.drawable.cell_shape);
		
			    row.addView(unitName);
			    row.addView(unitPrice);
			    row.addView(unitMetric);
			
			    
			    unitResultTable.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				
		 	}

	    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    	//Log.d("ADDFACTURE", "Reqest is " + requestCode + " code is "+ resultCode);
    	Boolean ifRecivedImage = false;
    	if (requestCode == GALLERY_REQUEST){    		
    		
    		Uri selectedimg = data.getData();

            try {
				factureImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedimg);
			} catch (FileNotFoundException e) {		
				e.printStackTrace();
			} catch (IOException e) {				
				e.printStackTrace();
			}
            
            ifRecivedImage = true;         
            Cursor cursor = null;
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(selectedimg,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            FactureIconPath =  cursor.getString(column_index);
   
    	}
    	else if (requestCode == CAMERA_REQUEST)
    	{
    		
    		 String[] projection = { MediaStore.Images.Media.DATA };
             Cursor cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  projection, null, null, null);
             int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
             cursor.moveToLast();
             FactureIconPath = cursor.getString(column_index_data);
             ifRecivedImage = true;             
             FactureIconPath =  moveFile(FactureIconPath, GlobalParams.getInstance().pathToExternalDir);

    	}
    	
    	if (ifRecivedImage){
    		//Small icon in imagebuuton
            /*int bytes = factureImage.getByteCount();  
            ByteBuffer buffer = ByteBuffer.allocate(bytes); 
            factureImage.copyPixelsToBuffer(buffer);
            byte[] FactureByteArray = buffer.array();           
    		Bitmap b = BitmapFactory.decodeByteArray(FactureByteArray, 0, FactureByteArray.length);
    		factureIcon.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false)); */       

    	}
    
    }   
	
	
	private String moveFile(String source, String dest) {
		
		InputStream inStream = null;
		OutputStream outStream = null;
	 
    	try{
		
			File afile =new File(source);
		    File bfile =new File(dest + File.separator + afile.getName());
	
		    inStream = new FileInputStream(afile);
		    outStream = new FileOutputStream(bfile);
	
		    byte[] buffer = new byte[1024];	
		    int length;		  
		    while ((length = inStream.read(buffer)) > 0){
	
		    	outStream.write(buffer, 0, length);
	
		    }	
		    inStream.close();
		    outStream.close();	
		  
		    afile.delete();
		    return bfile.getAbsolutePath();
		    
		    
		}catch(IOException e){
		    e.printStackTrace();
		}
		return source;	
    	
    	
    	
		
		
	}
		
		
	
	

}
